<template>
  <div>
    <el-form
      :model="createForm"
      label-width="90px"
      label-suffix=":"
      class="searchw"
      ref="createForm"
      :rules="rule"
    >
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="图片" prop="imgName" class="pictu">
            <!-- <el-upload class="upload-demo" ref="upload" action list-type="picture" :file-list="fileList"
                  :on-change="fileChange" :disabled="!isupload " accept="png,jpg"
                  :before-remove="beforeRemove">
                  <img v-if="createForm.imgName" :src="createForm.imgName" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload> -->
            <el-upload
              action="#"
              list-type="picture-card"
              :file-list="fileList"
              :disabled="isupload"
              accept="png,jpg"
              :before-remove="beforeRemove"
              :auto-upload="false"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model.trim="createForm.name"
              placeholder="请输入配件名称"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件属性" prop="matAttrCodeb">
            <el-cascader
              v-model="createForm.matAttrCodeb"
              :options="classifyList"
              :disabled="title == '配件详情'"
              :props="{
                value: 'id',
                label: 'lableName',
                children: 'childList',
                emitPath: false
              }"
            ></el-cascader>
            <!-- <el-select
                v-model="createForm.matAttrCodeb"
                size="medium"
                placeholder="请选择"
                filterable
                :disabled="title == '配件详情'"
              >
                <el-option
                  v-for="item in classifyList"
                  :key="item.id"
                  :label="item.name + ' - ' + item.parentName"
                  :value="item.id"
                />
              </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件类型" prop="materialType">
            <el-select
              v-model="createForm.materialType"
              size="medium"
              placeholder="请选择"
              filterable
              :disabled="title == '配件详情'"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="规格" prop="standard">
            <el-input
              v-model.trim="createForm.standard"
              placeholder="请输入规格"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="型号" prop="model">
            <el-input
              v-model.trim="createForm.model"
              placeholder="请输入型号"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位" prop="unit">
            <el-input
              v-model.trim="createForm.unit"
              placeholder="请输入单位"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="颜色" prop="color">
            <el-input
              v-model.trim="createForm.color"
              placeholder="请输入颜色"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="基础重量" prop="weight">
            <el-input
              v-model.trim="createForm.weight"
              placeholder="请输入基础重量"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制造商" prop="mfrs">
            <el-input
              v-model.trim="createForm.mfrs"
              placeholder="请输入制造商"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="拼音缩写" prop="pyName">
            <el-input
              v-model.trim="createForm.pyName"
              placeholder="请输入拼音缩写"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品条码" prop="barCode">
            <el-input
              v-model.trim="createForm.barCode"
              placeholder="请输入商品条码"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="原厂OE号" prop="oeCode">
            <el-input
              v-model.trim="createForm.oeCode"
              placeholder="请输入原厂OE号"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="上限" prop="upLimit">
            <el-input-number
              v-model.trim="createForm.upLimit"
              :min="0"
              label="请输入上限"
              :disabled="title == '配件详情'"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下限" prop="downLimit">
            <el-input-number
              v-model.trim="createForm.downLimit"
              :min="0"
              label="请输入下限"
              :disabled="title == '配件详情'"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="保质期天数" prop="expiryNum">
            <el-input-number
              v-model.trim="createForm.expiryNum"
              :min="0"
              label="请输入保质期天数"
              :disabled="title == '配件详情'"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8" v-if="title != '新增配件'">
          <el-form-item label="最低售价" prop="lowDecimal">
            <el-input
              v-model.trim="createForm.lowDecimal"
              placeholder="请输入最低售价"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model.trim="createForm.remark"
              placeholder="请输入备注"
              :disabled="title == '配件详情'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios'
import COS from 'cos-js-sdk-v5'
import { uploadFile } from '@/api/carLine'
const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'applyMain',
  props: {
    classifyList: {
      type: Array,
      default: []
    },
    createForm: {
      type: Object,
      default: {}
    },
    title: {
      type: String,
      default: ''
    }
  },
  watch: {
    createForm(val) {
      if (val.imgName instanceof Array) {
        this.initFileList(val.imgName.join(','))
      } else {
        this.initFileList(val.imgName)
      }
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      isupload: false,
      visible: true,
      typeList: [
        {
          id: '1',
          name: '零配件'
        },
        {
          id: '0',
          name: '其他配件'
        }
      ],
      rule: {
        name: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
        matAttrCodeb: [
          { required: true, message: '请选择配件属性', trigger: 'change' }
        ],
        materialType: [
          { required: true, message: '请选择配件类型', trigger: 'change' }
        ]
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    // getChange(val){
    //   this.createForm.matAttrCodeb = val[val.length - 1]
    // },
    getValidate() {
      let flag = null
      this.$refs['createForm'].validate((valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },
    /**
     *  上传头像
     */
    fileChange(file, fileList) {
      this.isupload = false
      let data = new FormData()
      data.append('biz', 'material')
      data.append('file', fileList[0].raw)
      uploadFile(data)
        .then((res) => {
          if (res.data.code == 0) {
            this.createForm.imgName = res.data.data.remoteUrl
            this.fileList = []
            this.isupload = true
          } else {
            this.$openMessage(res.data.message, 'error')
            this.isupload = true
          }
        })
        .catch((error) => {
          this.isupload = true
        })
    },
    /**
     * 上传文件前
     */
    beforeRemove() {
      this.fileList = []
    },
    initFileList(paths) {
      if (!paths || paths.length == 0) {
        this.fileList = []
        this.isupload = false
        return
      }
      this.isupload = true
      let fileList = []
      let arr = paths.split(',')
      var cos = new COS({
        getAuthorization: function (options, callback) {
          // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
          // 异步获取临时密钥
          axios
            .get(window.ipConfigUrl.cosUrl, {
              params: {
                prefix: 'images',
                type: 'getObject',
                bucketName: window.ipConfigUrl.cosBucket
              }
            })
            .then((res) => {
              if (res.data.code == 0) {
                var data = res.data.data
                console.log('数据：', data)
                callback({
                  TmpSecretId: data.tmpSecretId,
                  TmpSecretKey: data.tmpSecretKey,
                  SecurityToken: data.sessionToken,
                  // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                  StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                  ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000000              // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
                })
              }
            })
        }
      })
      for (var a = 0; a < arr.length; a++) {
        let path = arr[a]
        if (path) {
          cos.getObjectUrl(
            {
              Bucket:
                window.ipConfigUrl.cosBucket /* 填入您自己的存储桶，必须字段 */,
              Region:
                window.ipConfigUrl
                  .cosRegion /* 存储桶所在地域，例如ap-beijing，必须字段 */,
              Key: path /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
              Sign: true,
              onProgress: function (progressData) {
                console.log(JSON.stringify(progressData))
              }
            },
            function (err, data) {
              fileList.push({
                uid: uidGenerator(),
                name: getFileName(path),
                status: 'done',
                url: data.Url,
                response: {
                  code: 'history',
                  data: path,
                  Location: path
                }
              })
            }
          )
        }
      }
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
<style scoped lang="less">
.pictu {
  ::v-deep .el-upload--picture {
    width: 100px !important;
    height: 100px !important;
    line-height: 100px !important;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
}
.el-select,
.el-input-number,
.el-cascader--medium {
  width: 100% !important;
  .el-input {
    width: 100% !important;
  }
}
</style>
